<template>
  <div id="content">
    <el-card class="box-card">
      <el-form
        :model="loginData"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginData.username"
            autocomplete="off"
            width="400px"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginData.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >登录</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { login } from "@/api/userApi";
import { setToken } from "@/utils/auth";
export default {
  data() {
    return {
      loginData: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.loginData).then((res) => {
            if (res.code === 1000) {
              console.log(res);
              setToken(res.data.accessToken, res.data.refreshToken);
              this.$router.push("/");
            } else {
              this.$message({
                showClose: true,
                message: res.msg,
                type: "error",
              });
            }
          });
        } else {
          this.$message({
            showClose: true,
            message: "用户名或者密码不能为空，请确认重试",
            type: "error",
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  created: function () {
    // refreshToken().then((res) => {
    //   console.log(res);
    // });
  },
};
</script>
<style scoped>
#content {
  display: flex;
  justify-content: center;
  margin-top: 180px;
}
.box-card {
  width: 400px;
}
</style>